﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Windvoice.Blog;
using System.Threading;
using System.IO;
using System.Web.Script.Serialization;

namespace Windvoice.Areas.Manage.Controllers
{
    public class ArticleController : ManagerControllerBase
    {
        //
        // GET: /Manage/Blog/

        public ActionResult Index(int? page)
        {
            int PageIndex = page == null ? 1 : page.Value;
            int PageSize = 20;
            int RecordCount = 0;
            ViewBag.ArticleList = Article.GetList(PageIndex, PageSize, 0, out RecordCount);
            ViewBag.RecordCount = RecordCount;
            ViewBag.PageSize = PageSize;

            return View();
        }

        public ActionResult Create()
        {
            ViewBag.CategoryList = from c in Category.FindAll() select new SelectListItem() { Text = c.Name, Value = c.ID.ToString() };
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(Article article)
        {
            article.Hits = 0;
            article.CreateTime = DateTime.Now;

            if (ModelState.IsValid)
            {
                article.Create();
                return RedirectToAction("index");
            }

            ViewBag.CategoryList = from c in Category.FindAll() select new SelectListItem() { Text = c.Name, Value = c.ID.ToString() };
            return View();
        }

        public ActionResult Edit(int? id)
        {
            var article = id == null ? null : Article.Find(id.Value);
            if (article != null)
            {
                ViewBag.CategoryList = from c in Category.FindAll() select new SelectListItem() { Text = c.Name, Value = c.ID.ToString() };
                return View(article);
            }

            return View("_404");
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Article article)
        {
            var old = Article.Find(article.ID);
            article.CreateTime = old.CreateTime;
            article.Hits = old.Hits;
            if (ModelState.IsValid)
            {
                article.Update();
                return RedirectToAction("index");
            }
            else
            {
                ViewBag.CategoryList = from c in Category.FindAll() select new SelectListItem() { Text = c.Name, Value = c.ID.ToString() };
                return View(article);
            }
        }

        [HttpPost]
        public ActionResult Delete(FormCollection formValues)
        {
            if (!String.IsNullOrEmpty(formValues["id"]))
            {
                var ArticleID = Convert.ToInt32(formValues["id"]);
                Article.Find(ArticleID).Delete();
                return Json(new { result = true, message = String.Empty });
            }
            return AjaxResult(result: false, message: "参数错误！");
        }

        [HttpPost]
        public ActionResult CreateIndex(FormCollection formValues)
        {
            try
            {
                Article.CreateIndex();
                return AjaxResult();
            }
            catch (Exception ex)
            {
                return AjaxResult(result: false, message: ex.Message + "|||" + ex.StackTrace);
            } 
        }

        [HttpPost]
        public ActionResult Upload(FormCollection formValues)
        {
            var file = Request.Files["filedata"];

            if (file == null)
                return Content(new JavaScriptSerializer().Serialize(new { msg = String.Empty, err = "file null" }));


            //return Json(new { msg = String.Empty, err = Request.Files.Count +":"+ Server.MapPath("") });

            var guid = Guid.NewGuid().ToString();
            var ext = Path.GetExtension(file.FileName).ToLower().Substring(1);

            if (file != null && file.ContentLength > 0 && file.ContentLength <= 3 * 1024 * 1024 && new string[] { "jpg", "png", "gif" }.Contains(ext))
            {
                string RelativePath = String.Format("/files/blog/{0}/{1}.{2}", DateTime.Today.ToString("yyyyMM"), guid, ext);
                FileInfo AbsoluteFile = new FileInfo(Server.MapPath(RelativePath));
                if (!AbsoluteFile.Directory.Exists) AbsoluteFile.Directory.Create();

                file.SaveAs(AbsoluteFile.FullName);
                return Content(new JavaScriptSerializer().Serialize(new { msg = RelativePath, err = String.Empty }));
            }

            return Content(new JavaScriptSerializer().Serialize(new { msg = String.Empty, err = "file not allowed!" }));
        }
    }
}
